package com.ldy.gkrpc.client;

import com.ldy.gkrpc.codec.Decoder;
import com.ldy.gkrpc.codec.Encoder;
import com.ldy.gkrpc.common.utils.ReflectionUtils;

import java.lang.reflect.Proxy;
import java.rmi.server.RemoteObjectInvocationHandler;

/**
 * @Description
 * @Author
 * @Date 2020/4/15 20:10
 **/
public class RpcClient {
    private RpcClientConfig config;
    private Encoder encoder;
    private Decoder decoder;
    private TransportSelector selector;

    public RpcClient(){
        this(new RpcClientConfig());
    }

    public RpcClient(RpcClientConfig config) {
        this.config = config;
        this.encoder = ReflectionUtils.newInstance(config.getEncoderClass());
        this.decoder = ReflectionUtils.newInstance(config.getDecoderClass());
        this.selector = ReflectionUtils.newInstance(config.getSelectorClass());
        this.selector.init(config.getServers(),config.getConnectCount(),config.getTransportClientClass());

    }

    public <T> T getProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{clazz}, new RemoteInvocationHandler(clazz,this.encoder,this.decoder,this.selector));
    }
}
